/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package foxmob.mlts.model;

import foxmob.mlts.viewcontroller.student.QuestionPaperForm;
import java.awt.Color;
import java.awt.Event;
import java.awt.event.ActionEvent;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

/**
 *
 * @author zpf16z
 */
public class Timer extends Thread{  
    private JLabel clock;  
    private long time;  
    private long end;  
    private JButton submit;
    private JProgressBar jpb;
      
    public Timer(JLabel clock, JProgressBar processBar,long time, JButton submit){  
        this.clock = clock;   
        this.time = time;  
        this.submit = submit;
        this.jpb = processBar;
        init();
    }  

    public void init(){  
        long start = new Date().getTime();  
        end = start + time;  
    }     
    
    public void run(){  
        this.init();  
        while(true){  
            long now = new Date().getTime();  
            time = end - now;  
            if(time > 0){  
            //if (true){
                String s = this.convert(time);    
                clock.setText(s + "   ");
                int i = QuestionPaperForm.finishedQuestions;
                int j = QuestionPaperForm.questionNumber;
                int k = (int) (((float)i / (float)j) * 100);
                jpb.setValue(k);
                jpb.setStringPainted(true);
                jpb.setString(i + " / " + j);
                //jpb.repaint();
            }else{  
                //StudentsForm
                break;    
            }  
            try{  
                Thread.sleep(10);     
            }catch(InterruptedException e){  
                e.printStackTrace();      
            }  
        }  
        clock.setText("Time Over!     "); 
        submit.doClick();
        clock.setBackground(Color.RED);  
    }   
    
    public String convert(long time){  
        long h = time / 3600000;  
        long m = (time % 3600000) / 60000;  
        long s = (time % 60000) / 1000;  
        //long ms = (time % 1000) / 10;  
        String ph = h<10 ? "0":"";  
        String pm = m<10 ? "0":"";  
        String ps = s<10 ? "0":"";     
        //String pms = ms<10 ? "0":"";   
        String txt = ph + h + ":" + pm + m + ":" + ps + s; //+ "." + pms + ms;   
        return txt;  
    }     
} 
